<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-30 18:02:50
 * @LastEditors: zhangjx
 * @LastEditTime: 2023-06-06 17:26:40
-->
<template>
	<div class="active-item mt10">
		<el-card>
			<template #header>
				<div class="card-header">
					<div class="fc">
						<icon-attention theme="outline" />
						<p class="text-grey f14">您可以搜索一个现有的角色，复制它的菜单内容，再次基础上进行修改</p>
					</div>
					<AplidRemote
						style="width: 100%"
						v-model="roleValue"
						api="sys_role_page"
						:filterable="true"
						@update:model-value="onChange"
						placeholder="请输入角色名称"
						filterLabel="roleName"
						filterKey="roleId"
					></AplidRemote>
				</div>
			</template>
			<MenuTree class="mt10" ref="treeRef" api="admin_menu" @tree-load="onTreeLoad" :deviceType="deviceType"></MenuTree>
		</el-card>
	</div>
</template>

<script setup lang="ts">
import AplidRemote from '@/components/AplidCrud/src/AplidRemote/index'
import MenuTree from '../MenuTree/index.vue'
import apiMod from '@/apiMod/index'
import {ElMessage} from 'element-plus'

const emit = defineEmits(['refresh'])
const roleValue = ref('')
const treeRef = ref(null)
const props = defineProps({
	roleId: [String, Number],
	deviceType: [String, Number],
})

const updateRoleMenu = () => {
	const menuIdArr = treeRef.value?.getCheckedKeys() || []
	if (menuIdArr.length > 0) {
		const query = {
			deviceType: props.deviceType,
			menuIds: menuIdArr.join(','),
			roleId: props.roleId,
		}
		apiMod.sys_role_perm(query).then((res) => {
			ElMessage.success('设置成功!')
			if (props.roleId) onChange(props.roleId)
			emit('refresh')
		})
	} else {
		ElMessage.warning('请先勾选需要设置的菜单!')
	}
}
const onChange = (roleId) => {
	if (roleId) {
		apiMod
			.sysRoleGetMenuIds({
				deviceType: props.deviceType,
				roleId: roleId,
			})
			.then((res) => {
				treeRef.value?.setCheckedKeys(res.data)
			})
	}
}
const onTreeLoad = () => {
	setTimeout(() => {
		if (props.roleId) onChange(props.roleId)
	}, 0)
}

defineExpose({
	updateRoleMenu,
})
</script>

<style scoped></style>
